package com.hg.controller;


import com.hg.common.HttpStatus;
import com.hg.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@CrossOrigin
@PropertySource("classpath:jdbc.properties")
public class CommonsController {

    /**
     * 储存图片的基本路径
     * 基本路径
     */

//    private static final String basePath = "D:\\hgimgs\\";
    @Value("${files.upload.path}")
    private String basePath;
    /**
     * 文件上传
     *
     * @param file 文件
     * @return {@link R}<{@link String}>
     */
    @PostMapping("/upload")
    public R<String> uploadImg(@RequestParam("file") MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        String fileName =uuid+suffix;
        File dir =new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(HttpStatus.COMMON_SUCCESS,"",fileName);
    }


    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws Exception {
        BufferedInputStream bufferedInputStream =new BufferedInputStream(new FileInputStream(basePath+name));
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        byte[] bytes=new byte[1024];
        int len =0;
        while ((len=bufferedInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        bufferedInputStream.close();
        outputStream.close();
    }


    @DeleteMapping("/deleteImg/{img}")
    public void deleteImg(@PathVariable String icon){
        icon="D:\\hgimgs\\"+icon+".jpg";
        File file = new File(icon);
        if (file.exists()){
            file.delete();
        }
    }
}
